package org.wyf.EveryPoint.system.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;
import org.wyf.EveryPoint.common.annotation.Limit;
import org.wyf.EveryPoint.common.controller.BaseController;
import org.wyf.EveryPoint.common.entity.FebsResponse;
import org.wyf.EveryPoint.common.exception.FebsException;
import org.wyf.EveryPoint.common.properties.FebsProperties;
import org.wyf.EveryPoint.common.service.ValidateCodeService;
import org.wyf.EveryPoint.common.utils.Md5Util;
import org.wyf.EveryPoint.monitor.service.ILoginLogService;
import org.wyf.EveryPoint.system.entity.User;
import org.wyf.EveryPoint.system.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.Map;

/**
 * @author MrBird
 */
@Validated
@RestController
@RequiredArgsConstructor
public class LoginController extends BaseController {

    private final IUserService userService;
    private final ValidateCodeService validateCodeService;
    private final ILoginLogService loginLogService;
    private final FebsProperties properties;

    /**
     * 后台登录,只有管理员和创作者才能登录
     * @param username
     * @param password
     * @param verifyCode
     * @param rememberMe
     * @param request
     * @return
     * @throws FebsException
     */
    @PostMapping("login")
    @Limit(key = "login", period = 60, count = 10, name = "登录接口", prefix = "limit")
    public FebsResponse login(
            @NotBlank(message = "{required}") String username,
            @NotBlank(message = "{required}") String password,
            @NotBlank(message = "{required}") String verifyCode,
            boolean rememberMe, HttpServletRequest request) throws FebsException {
        validateCodeService.check(request.getSession().getId(), verifyCode);
        User user = userService.findByName(username);
        if (user.getIsAdmin() != null && user.getIsCreate() != null){
            if (!user.getIsCreate().equals("1") && !user.getIsAdmin().equals("1")) {
                throw new FebsException("非管理员和创作者,不能登录后台");
            }
        }else {
            throw new FebsException("账号有误，请联系管理员");
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username,
                Md5Util.encrypt(username.toLowerCase(), password), rememberMe);
        super.login(token);
        // 保存登录日志
        loginLogService.saveLoginLog(username);
        return new FebsResponse().success().data("index");
    }


    @PostMapping("register")
    public FebsResponse register(
            @NotBlank(message = "{required}") String username,
            @NotBlank(message = "{required}") String password) throws FebsException {
        User user = userService.findByName(username);
        if (user != null) {
            throw new FebsException("该用户名已存在");
        }
        userService.register(username, password);
        return new FebsResponse().success();
    }

    @GetMapping("index/{username}")
    public FebsResponse index(@NotBlank(message = "{required}") @PathVariable String username) {
        // 更新登录时间
        userService.updateLoginTime(username);
        // 获取首页数据
        Map<String, Object> data = loginLogService.retrieveIndexPageData(username);
        return new FebsResponse().success().data(data);
    }

    @GetMapping("images/captcha")
    @Limit(key = "get_captcha", period = 60, count = 10, name = "获取验证码", prefix = "limit")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException, FebsException {
        validateCodeService.create(request, response);
    }

    /**
     * 前端用户登录
     * @param username
     * @param password
     * @param verifyCode
     * @param rememberMe
     * @param request
     * @return
     * @throws FebsException
     */
    @PostMapping("/web/common/login")
    @Limit(key = "login", period = 60, count = 10, name = "前端登录接口", prefix = "limit")
    public FebsResponse webLogin(
            @NotBlank(message = "{required}") String username,
            @NotBlank(message = "{required}") String password,
            @NotBlank(message = "{required}") String verifyCode,
            boolean rememberMe, HttpServletRequest request) throws FebsException {
        validateCodeService.check(request.getSession().getId(), verifyCode);

        UsernamePasswordToken token = new UsernamePasswordToken(username,
                Md5Util.encrypt(username.toLowerCase(), password), rememberMe);

        super.login(token);
        // 保存登录日志
        loginLogService.saveLoginLog(username);
       User user = getCurrentUser();
        if (user.getIsAdmin() != null && user.getIsCreate() != null){
            if (user.getIsAdmin().equals("1")) {
                return new FebsResponse().success().data("index");
            }
        }
        return new FebsResponse().success().data("web/common/index");
    }

    @PostMapping("/web/common/register")
    public FebsResponse webRegister(
            @NotBlank(message = "{required}") String username,
            @NotBlank(message = "{required}") String password,
            @NotBlank(message = "{required}") String verifyCode,
            HttpServletRequest request) throws FebsException {
        validateCodeService.check(request.getSession().getId(), verifyCode);
        User user = userService.findByName(username);
        if (user != null) {
            throw new FebsException("该用户名已存在");
        }
        userService.webRegister(username, password);
        return new FebsResponse().success();
    }
}
